import collections

from timeit import default_timer

from twisted.python import log

from fjork import settings


def logFunctionTime(function):
    if settings.DEBUG:
        def timedFunction(*args, **kwargs):
            start = default_timer()
            result = function(*args, **kwargs)
            end = default_timer() - start
            log.msg(
                '%s.%s executed in %f seconds' % (
                    function.__module__, function.__name__, end
                )
            )
            return result
        return timedFunction
    else:
        return function


def logMethodTime(method):
    if settings.DEBUG:
        def timedMethod(self, *args, **kwargs):
            start = default_timer()
            result = method(self, *args, **kwargs)
            end = default_timer() - start
            log.msg(
                '%s.%s.%s executed in %f seconds' % (
                    method.__module__,
                    self.__class__.__name__,
                    method.__name__,
                    end
                )
            )
            return result
        return timedMethod
    else:
        return method


def roundrobin(*iterables):
    pending = collections.deque(iter(i) for i in iterables)
    while pending:
        task = pending.popleft()
        try:
            yield task.next()
        except StopIteration:
            continue
        pending.append(task)
